package middlewares

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

var (
	JWTMan *JWTManager
)

func init() {
	JWTMan = NewJWTManager()
	JWTMan.Init()
}

//jwt中间件
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		//拿到token
		token := c.Request.Header.Get("token")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"msg": "未认证",
			})
			c.Abort()
			return
		}
		//token无效
		_, err := JWTMan.Parse(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"msg": err.Error(),
			})
			c.Abort()
			return
		}
		log.Println("？使用token鉴权了")
		c.Next()
	}
}
